package com.dongdongshop.controller;

import com.dongdongshop.constant.SeckillConstant;
import com.dongdongshop.enums.ResultEnum;
import com.dongdongshop.pojo.TbSeckillGoods;
import com.dongdongshop.pojo.TbUser;
import com.dongdongshop.service.SeckillService;
import com.dongdongshop.util.Result;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("seckill")
public class SeckillController {

    @DubboReference
    private SeckillService seckillService;

    @Autowired
    private RedisTemplate redisTemplate;

    //缓存预热:提前将要秒杀的商品 放入缓存,防止出现缓存击穿,雪崩现象
    //TODO
    @RequestMapping("index")
    public String index() {
        return "seckill-index";
    }



    @RequestMapping("preHotCache")
    @ResponseBody
    public Result preHotCache(){
        seckillService.preHotCache();
        return Result.OK();
    }

    @RequestMapping("seckillList")
    @ResponseBody
    public Result seckillList(){
        List<TbSeckillGoods> seckillGoodsList = seckillService.seckillList();
        return Result.OK().setData(seckillGoodsList);
    }

    @RequestMapping("item/{id}")
    public String item(@PathVariable("id") Long id,Model m) {
        TbSeckillGoods goods = seckillService.selectSeckillById(id);
        m.addAttribute("goods", goods);
        return "seckill-item";
    }
    
    
    @RequestMapping("createOrder")
    @ResponseBody
    public Result createOrder(Long seckillGoodsId){
        //判断用户是否登录
        TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
        if (user == null){
            return Result.response(ResultEnum.USER_ERROR_NULL);
        }
        try {
            seckillService.createOrder(user,seckillGoodsId);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.ERROR();
        }
        return Result.OK();
    }

    @RequestMapping("getOrderId")
    @ResponseBody
    public Result getOrderId(){
        TbUser user = (TbUser) SecurityUtils.getSubject().getPrincipal();
        if (user == null){
            return Result.response(ResultEnum.USER_ERROR_NULL);
        }
        Long orderId = (Long) redisTemplate.boundValueOps(SeckillConstant.SECKILL_ORDER + user.getUsername()).get();
        if (orderId == null){
            return Result.ERROR();
        }
        return Result.OK().setData(orderId.toString());
    }
}
